package com.han.controllers.export;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jmesa.core.filter.MatcherKey;
import org.jmesa.core.filter.NumberFilterMatcher;
import org.jmesa.limit.ExportType;
import org.jmesa.model.TableModel;
import org.jmesa.view.component.Column;
import org.jmesa.view.component.Row;
import org.jmesa.view.component.Table;
import org.jmesa.view.editor.CellEditor;
import org.jmesa.view.html.HtmlBuilder;
import org.jmesa.view.html.component.HtmlColumn;
import org.jmesa.view.html.component.HtmlRow;
import org.jmesa.view.html.component.HtmlTable;

import com.han.bom.Exam;
import com.han.bom.MultipleChoice;
import com.han.bom.Question;
import com.han.bom.utilities.ExamCategory;
import com.han.dao.concrete.product.AnswerDAO;
import com.han.dao.concrete.product.ExamDAO;
import com.han.dao.concrete.product.QuestionDAO;

/**
 * Servlet implementation class JMesaExportExamsServlet
 */
@WebServlet("/Professor/JMesaExportExamsServlet")
public class JMesaExportExamsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JMesaExportExamsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		ExamDAO examdao = new ExamDAO();
		QuestionDAO questiondao = new QuestionDAO();
		AnswerDAO answerdao = new AnswerDAO();
		
		ArrayList<ExamCategory> examCategory = new ArrayList<ExamCategory>();
		
		try {
			for(Exam exam: examdao.retrieveAllExams()){
			
				ArrayList<Question> questions = questiondao.retrieveQuestionsbyExam(exam.getExamID());
				
				for(Question question: questions){
					ArrayList<String> choices = answerdao.retrieveAnswersByQuestion(question.getQuestionID());
					
					question.setAnswer(choices.get(0));
					
					if(question instanceof MultipleChoice){
						Collections.sort(choices);
					}
					else{
						Collections.sort(choices);
						Collections.reverse(choices);
					}
				}
				
				ArrayList<String> categories = questiondao.retrieveCategoriesbyExam(exam.getExamID());
				
				exam.setQuestions(questions);
				examCategory.add(new ExamCategory(exam, categories));
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		TableModel tableModel = new TableModel("table", request, response);
		
		tableModel.setExportTypes(ExportType.CSV,ExportType.JEXCEL,ExportType.PDFP);
		tableModel.setItems(examCategory);
		
		if(tableModel.isExporting()){
			Table Table = new Table().caption("Examinee-Exam Record");
			
			Row Row = new Row();
			Table.setRow(Row);
			
			Column idCol = new Column("examID").title("Exam ID");
			Row.addColumn(idCol);
	
			Column lastNameCol = new Column("examName").title("Exam Name");
			Row.addColumn(lastNameCol);
	
			Column termCol = new Column("duration").title("Duration");
			tableModel.addFilterMatcher(new MatcherKey(Long.class, "duration"), new NumberFilterMatcher("####"));
			Row.addColumn(termCol);
	
			Column careerCol = new Column("itemCount").title("# of Items");
			tableModel.addFilterMatcher(new MatcherKey(Integer.class, "itemCount"), new NumberFilterMatcher("####"));
			Row.addColumn(careerCol);
			
	    	Column passingCol = new Column("passing").title("Passing Grade");
	    	tableModel.addFilterMatcher(new MatcherKey(Double.class, "passing"), new NumberFilterMatcher("###.##"));
	    	Row.addColumn(passingCol);
	
			tableModel.setTable(Table);
			
			String export = tableModel.render();
			
			request.setAttribute("table",export);
		}
		else{
			HtmlTable htmlTable = new HtmlTable();
			
			HtmlRow htmlRow = new HtmlRow();
			htmlTable.setRow(htmlRow);
						
			HtmlColumn examIDCol = new HtmlColumn("examID").title("Exam ID");
	    	htmlRow.addColumn(examIDCol); 
	
			HtmlColumn examNameCol = new HtmlColumn("examName").title("Exam Name");
	    	htmlRow.addColumn(examNameCol);
	    	
	    	HtmlColumn durationCol = new HtmlColumn("duration").title("Duration");
	    	tableModel.addFilterMatcher(new MatcherKey(Long.class, "duration"), new NumberFilterMatcher("####"));
	    	htmlRow.addColumn(durationCol);
	
	    	HtmlColumn itemCountCol = new HtmlColumn("itemCount").title("# of Items");
	    	tableModel.addFilterMatcher(new MatcherKey(Integer.class, "itemCount"), new NumberFilterMatcher("####"));
	    	htmlRow.addColumn(itemCountCol);
	    	
	    	HtmlColumn passingCol = new HtmlColumn("passing").title("Passing Grade");
	    	tableModel.addFilterMatcher(new MatcherKey(Double.class, "passing"), new NumberFilterMatcher("###.##"));
	    	htmlRow.addColumn(passingCol);
	    	
	    	HtmlColumn categoryCol = new HtmlColumn("categories").title("Categories");
	    	htmlRow.addColumn(categoryCol);
	    	
	    	HtmlColumn viewLink = new HtmlColumn("name").title("View");
	    	viewLink.setCellEditor(new CellEditor() {             
				public Object getValue(Object item, String property, int rowcount) {                 
	    			//Object value = new HtmlCellEditor().getValue(item, property, rowcount);                 
	    			HtmlBuilder html = new HtmlBuilder();
	    			ExamCategory er = (ExamCategory)item;
	    			html.a().href().quote().append("JMesaExportStudentExamListServlet?id="+er.getExamID()).quote().close();
	    			html.append("View Examinees");
	    			html.aEnd();
	    			return html.toString();             
	    			}         
	    		});
	    	viewLink.setSortable(false);
	    	viewLink.setFilterable(false);
	    	htmlRow.addColumn(viewLink); 
	    	
			tableModel.setTable(htmlTable);
	
			String html = tableModel.render();
			
			request.setAttribute("table",html);
			
			RequestDispatcher rd = request.getRequestDispatcher("Report_Exams.jsp");
			rd.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
